package com.lnsoft.dqfs.client.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lnsoft.dqfs.server.util.MessageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientReadHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private static final Logger logger = LoggerFactory.getLogger(ClientReadHandler.class);


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        if((byteBuf.getByte(0) & 0xFF)==16){
            byte[] bytes = new byte[6];
            byteBuf.readBytes(bytes);
            if((bytes[1] & 0xFF)==73){
                channelHandlerContext.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[]{16, (byte) 139, 71, 35, (byte) 245, 22}));
            }else if((bytes[1] & 0xFF)==64){
                channelHandlerContext.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[]{16, (byte) 128, 71, 35, (byte) 234, 22}));
                channelHandlerContext.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[]{104, 11, 11, 104, (byte) 211, 71, 35, 70, 1, 4, 71, 35, 0, 0, 0, (byte) 242, 22}));
            }else if((bytes[1] & 0xFF)==114){
                logger.debug("心跳请求");
                channelHandlerContext.channel().writeAndFlush(
                        Unpooled.wrappedBuffer( new byte[]{16, (byte) 128, 71, 35, (byte) 234, 22}));
            }
        }else{
            byte[] timeBytes = new byte[23];
            byteBuf.readBytes(timeBytes);
            channelHandlerContext.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[]{16, (byte) 128, 71, 35, (byte) 234, 22}));
            timeBytes[4] = MessageUtil.createClientC((byte) 1, (byte) 1, (byte) 3);
            timeBytes[timeBytes.length - 2] = (byte) MessageUtil.createCS(timeBytes, 4, timeBytes.length - 2);
            channelHandlerContext.channel().writeAndFlush(Unpooled.wrappedBuffer(timeBytes));

        }

    }
}
